package com.zh.work.controller.platform.branch;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zh.common.annotaion.CurieCache;
import com.zh.work.constant.BranchInfoConstants;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zh.work.dao.platform.branch.BranchInfoMapper;
import com.zh.work.entity.branch.BranchInfoEntity;
import com.zh.work.entity.branch.QrcodeBranchFee;
import com.zh.common.entity.JSONResult;
import com.zh.common.entity.Oauth;
import com.zh.work.service.platform.branch.BranchInfoService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import java.util.*;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description: Info管理
 * @Author: Li.HuiNeng
 * @Create in: 2019/08/23
 * @Version: 1.0.1
 */
//@PreAuthorize("hasAuthority('/branch_set/brc_info')")
@Api(value = "Info管理控制器", produces = "application/json", tags = {"Info管理控制器"})
@RestController
@RequestMapping("/info")
public class BranchInfoController {
    private static final Logger log = LoggerFactory.getLogger(BranchInfoController.class);

    /**
     * @Description: 简易crud时使用
     * ------------------------
     * @Author: Li.HuiNeng
     * @Date: 2019/08/23
     */
    @Autowired
    private BranchInfoMapper mapper;

    /**
     * @Description: 有业务逻辑需要处理时使用
     * ------------------------
     * @Author: Li.HuiNeng
     * @Date: 2019/08/23
     */
    @Autowired
    private BranchInfoService service;

    @Autowired
    private RedisTemplate redisTemplate;


    //    @PreAuthorize("hasAuthority('/branch_set/brc_info/add')")
    @ApiOperation(value = "新增一条记录", tags = {"putAddInfo"}, notes = "新增一条记录,请使用application/json格式提交哦!")
    @PutMapping("/putAddInfo")
    @ResponseBody
    @Transactional
    public JSONResult<BranchInfoEntity> putAddInfo(@ApiParam(value = "机构信息实体类", name = "branchInfoEntity") @RequestBody BranchInfoEntity branchInfoEntity) {
        JSONResult<BranchInfoEntity> jsonResult = new JSONResult<>();
        // 处理省市联动
        List<String> strArr = JSON.parseArray(branchInfoEntity.getProvinceCity(), String.class);
        try {
            branchInfoEntity.setProvince(strArr.get(0));
            branchInfoEntity.setCity(strArr.get(1));
            branchInfoEntity.setAreaCode(strArr.get(2));
            // 机构编号拼接
            String branchNo = "0" + branchInfoEntity.getBizCode() + strArr.get(2);
            branchInfoEntity.setBranchNo(branchNo);
            // 分解二维码成本信息
            List<QrcodeBranchFee> list = JSON.parseArray(branchInfoEntity.getBranchFee(), QrcodeBranchFee.class);
            if (list != null) {
                if (list.size() > 0) {
                    list.forEach(l -> l.setBranchNo(branchNo));
                    // 批量插入当前机构的二维码成本信息
                    this.service.addQrBrcFee(list);
                }
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("二维码成本为空!");
            }
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("请填写完整的联系地址与详细地址!");
            log.error(e.getLocalizedMessage());
            return jsonResult;
        }
        // 处理
        try {
            if (branchInfoEntity.insert()) {
                // 返回新增主键
//                System.out.println(branchInfoEntity.getId());
                jsonResult.setCode(200);
                jsonResult.setMessage("添加完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("添加失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setCode(e.hashCode());
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }


    //    @PreAuthorize("hasAuthority('/branch_set/brc_info/update')")
    @ApiOperation(value = "通过id修改信息", tags = {"putModInfoById"}, notes = "通过id修改信息,请使用application/json格式提交哦!")
    @PutMapping("/putModInfoById")
    @ResponseBody
    public JSONResult<BranchInfoEntity> putModInfoById(@ApiParam(value = "机构信息实体类", name = "branchInfoEntity") @RequestBody BranchInfoEntity branchInfoEntity) {
        JSONResult<BranchInfoEntity> jsonResult = new JSONResult<>();
        // 分解二维码成本信息
        List<QrcodeBranchFee> list = JSON.parseArray(branchInfoEntity.getBranchFee(), QrcodeBranchFee.class);
        // 查询机构二维码成本数量
        Map<String, Long> map = mapper.getBranchQrCodeFeeNum(branchInfoEntity.getBranchNo());
        // 批量删除
        if (map != null) {
            if (map.get("num") != 0) {
                this.service.delQrBrcFee(branchInfoEntity.getBranchNo());
            }
        }
        if (list != null) {
            if (list.size() > 0) {
                list.forEach(l -> l.setBranchNo(branchInfoEntity.getBranchNo()));
                // 批量插入当前机构的二维码成本信息
                this.service.addQrBrcFee(list);
            }
        }
        try {
            if (branchInfoEntity.updateById()) {
                jsonResult.setCode(200);
                jsonResult.setMessage("修改完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("修改失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setCode(e.hashCode());
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }

    //    @PreAuthorize("hasAuthority('/branch_set/brc_info/del')")
    @ApiOperation(value = "根据主键删除记录", tags = {"deleteInfoById"}, notes = "根据主键删除记录")
    @DeleteMapping("/deleteInfoById")
    public JSONResult<BranchInfoEntity> deleteInfoById(@ApiParam(value = "机构信息实体类", name = "branchInfoEntity") BranchInfoEntity branchInfoEntity) {
        JSONResult<BranchInfoEntity> jsonResult = new JSONResult<>();
        try {

            if (branchInfoEntity.deleteById()) {
                jsonResult.setCode(200);
                jsonResult.setMessage("删除完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("删除失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setCode(e.hashCode());
            e.printStackTrace();
        }
        return jsonResult;
    }

    //    @PreAuthorize("hasAuthority('/branch_set/brc_info/dels')")
    @ApiOperation(value = "根据主键列表批量删除记录", tags = {"deleteInfoBatchByIds"}, notes = "该传参时 请选择raw(application/json)格式传入," +
            "举例需删除id为1和2的信息时,参数传入[1,2]即可")
    @DeleteMapping("/deleteInfoBatchByIds")
    @ResponseBody
    public JSONResult<BranchInfoEntity> deleteInfoBatchByIds(@ApiParam(value = "主键集合", name = "ids") @RequestBody @RequestParam("ids") List<Integer> ids) {
        JSONResult<BranchInfoEntity> jsonResult = new JSONResult<>();
        try {
            int c = this.mapper.deleteBatchIds(ids);
            if (c > 0) {
                jsonResult.setCode(200);
                jsonResult.setMessage("删除完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("删除失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setCode(e.hashCode());
            e.printStackTrace();
        }
        return jsonResult;
    }


    //    @PreAuthorize("hasAuthority('/branch_set/brc_info/get')")
    @ApiOperation(value = "根据机构编号获取机构信息", tags = {"getInfoByBranchNo"}, notes = "根据机构编号获取机构信息")
    @GetMapping("/getInfoByBranchNo")
    public JSONResult<BranchInfoEntity> getInfoByBranchNo(@ApiParam(value = "机构信息实体类", name = "branchInfoEntity") BranchInfoEntity branchInfoEntity) {
        JSONResult<BranchInfoEntity> jsonResult = new JSONResult<>();
        try {
            BranchInfoEntity result = service.getOne(new LambdaQueryWrapper<BranchInfoEntity>()
                    .eq(BranchInfoEntity::getBranchNo, branchInfoEntity.getBranchNo()));
            if (result != null) {
                jsonResult.setCode(200);
                jsonResult.setMessage("查询完成");
                jsonResult.setSuccess(true);
                jsonResult.setData(result);
            } else {
                jsonResult.setMessage("未查询到相应信息，请检查参数是否正确");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setCode(e.hashCode());
            e.printStackTrace();
        }
        return jsonResult;
    }


    //    @PreAuthorize("hasAuthority('/branch_set/brc_info/get')")
    @ApiOperation(value = "分页查询参数数据集", tags = {"getPagesInfos"}, notes = "分页查询参数数据集")
    @GetMapping("/getPagesInfos")
//    @CurieCache
    public JSONResult<List<BranchInfoEntity>> getPagesInfos(
            @ApiParam(value = "起始页", name = "pageNo") Integer pageNo,
            @ApiParam(value = "显示数量页数", name = "pageNo") Integer pageSize,
            @ApiParam(value = "机构信息实体类", name = "branchInfoEntity") BranchInfoEntity branchInfoEntity) {
        JSONResult<List<BranchInfoEntity>> jsonResult = new JSONResult<>();
        try {
            IPage<BranchInfoEntity> page = this.mapper.selectPage(
                    new Page<>(pageNo, pageSize),
                    new QueryWrapper<BranchInfoEntity>()
                            .like(StringUtils.isNotEmpty(branchInfoEntity.getBranchNo()), "branchno", branchInfoEntity.getBranchNo())
                            .like(StringUtils.isNotEmpty(branchInfoEntity.getBranchName()), "branch_name", branchInfoEntity.getBranchName())
                            .like(StringUtils.isNotEmpty(branchInfoEntity.getBranchFull()), "branch_full", branchInfoEntity.getBranchFull())
            );
            jsonResult.setTotal(page.getTotal());
            jsonResult.setData(page.getRecords());
            jsonResult.setMessage("操作成功");
            jsonResult.setSuccess(true);
            jsonResult.setCode(200);
        } catch (Exception e) {
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }


    //    @PreAuthorize("hasAuthority('/branch_set/brc_info/codeFee')")
    @ApiOperation(value = "获取指定机构的二维码费率列表信息", tags = {"getBranchQrFeeByBrc"}, notes = "获取指定机构的二维码费率列表信息")
    @GetMapping("/getBranchQrFeeByBrc")
    public JSONResult<Object> getBranchQrFeeByBrc(@ApiParam(value = "机构编号", name = "branchNo") @RequestParam("branchNo") String branchNo) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        if (!StringUtils.isNotEmpty(branchNo)) {
            jsonResult.setMessage("抱歉!机构编号为空,无法查询.");
        }
        List<QrcodeBranchFee> list = this.service.getQrCodeRate(branchNo);
        if (list.size() > 0) {
            jsonResult.setSuccess(true);
            jsonResult.setData(list);
        } else {
            jsonResult.setSuccess(false);
            jsonResult.setData(null);
            jsonResult.setMessage("未查找到编号为【" + branchNo + "】机构的二维码费率信息!");
        }
        return jsonResult;
    }


    //    @PreAuthorize("hasAuthority('/branch_set/brc_info/qrFee')")
    @ApiOperation(value = "获取系统开户银行信息", tags = {"getBankInfo"}, notes = "searchType(1.按省市筛选,2.按关键字筛选)")
    @GetMapping("/getBankInfo")
    public JSONResult<Object> getBankInfo(@ApiParam(value = "搜索类型", name = "searchType") @RequestParam(value = "searchType", defaultValue = "1") String searchType,
                                          @ApiParam(value = "开户行名称", name = "bankName") @RequestParam(value = "bankName", defaultValue = "") String bankName,
                                          @ApiParam(value = "开户行编码", name = "bankCode") @RequestParam(value = "bankCode", defaultValue = "") String bankCode,
                                          @ApiParam(value = "省市区编码", name = "province") @RequestParam(value = "province", defaultValue = "") String province,
                                          @ApiParam(value = "城市编码", name = "city") @RequestParam(value = "city", defaultValue = "") String city) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        jsonResult.setSuccess(true);
        Map<String, Object> map = this.service.getBankList(searchType, bankName, bankCode, province, city);
        jsonResult.setData(map);
        return jsonResult;
    }

    @ApiOperation(value = "获取机构列表", tags = {"getBranchList"}, notes = "获取机构列表")
    @GetMapping("/getBranchList")
    public JSONResult<List<BranchInfoEntity>> getBranchList(@ApiParam(value = "是否根据用户权限查询Y:需要", name = "isAuth")
                                                            @RequestParam(value = "isAuth", required = false) String isAuth) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Oauth auth = (Oauth) authentication.getPrincipal();
        JSONResult<List<BranchInfoEntity>> jsonResult = new JSONResult<>();
        List<BranchInfoEntity> list = new ArrayList<>();
        try {
            if (Objects.nonNull(isAuth)) {
                this.redisTemplate.delete(BranchInfoConstants.INFO_UPDATE_REDIS);
            }
            list = JSON.parseArray(JSON.toJSONString(this.redisTemplate.opsForValue().get(BranchInfoConstants.INFO_UPDATE_REDIS)), BranchInfoEntity.class);
            if (Objects.isNull(list)) {
                list = this.mapper.getBranchListByAuth(isAuth, String.valueOf(auth.getId()));
            }
            jsonResult.setSuccess(true);
            jsonResult.setData(list);
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }


    @ApiOperation(value = "获取指定账户对应角色绑定的信息", tags = {"getAcRoleBindList"}, notes = "绑定账户角色")
    @GetMapping("/getAcRoleBindList")
    public JSONResult<Object> getAcRoleBindList(@RequestParam(required = false) String typeId,
                                                @RequestParam(required = false) String forfeignId) {
        Oauth principal = (Oauth) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        JSONResult jsonResult = new JSONResult();
        HashMap<String, String> map = new HashMap<>();
        map.put("typeId", typeId);
        map.put("forfeignId", forfeignId);
        Map<String, Object> map1 = new HashMap<>();
        try {
//            if (principal.getUserLoginName().equals("admin")) {
//                jsonResult.setData(redisTemplate.opsForValue().get("admin"));;
//            } else {
            map1 = service.getRoleBindList(map);
            if (map1 != null) {
                jsonResult.setSuccess(true);
                jsonResult.setMessage("ok");
                jsonResult.setData(map1);
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("未查询到当前登录账户下属列表。");
            }
//            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

}
